package com.demo.product.service;

import com.alibaba.fastjson.JSON;
import com.demo.product.config.RabbitMQConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 秒杀消息服务
 * 负责发送秒杀订单消息到RabbitMQ
 */
@Service
public class SeckillMessageService {

    private static final Logger log = LoggerFactory.getLogger(SeckillMessageService.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送秒杀订单消息
     * @param userId 用户ID
     * @param productId 商品ID
     * @param quantity 购买数量
     */
    public void sendSeckillOrderMessage(Long userId, Long productId, Integer quantity) {
        try {
            // 构建消息内容
            Map<String, Object> message = new HashMap<>();
            message.put("userId", userId);
            message.put("productId", productId);
            message.put("quantity", quantity);
            message.put("timestamp", LocalDateTime.now().toString());
            message.put("messageId", System.currentTimeMillis() + "_" + userId + "_" + productId);
            
            String messageJson = JSON.toJSONString(message);
            
            // 发送消息到RabbitMQ
            rabbitTemplate.convertAndSend(
                RabbitMQConfig.SECKILL_EXCHANGE,
                RabbitMQConfig.SECKILL_ROUTING_KEY,
                messageJson
            );
            
            log.info("秒杀订单消息发送成功，userId: {}, productId: {}, quantity: {}", 
                    userId, productId, quantity);
            
        } catch (Exception e) {
            log.error("秒杀订单消息发送失败，userId: {}, productId: {}, quantity: {}", 
                    userId, productId, quantity, e);
            throw new RuntimeException("消息发送失败", e);
        }
    }

    /**
     * 发送秒杀失败消息
     * @param userId 用户ID
     * @param productId 商品ID
     * @param reason 失败原因
     */
    public void sendSeckillFailMessage(Long userId, Long productId, String reason) {
        try {
            Map<String, Object> message = new HashMap<>();
            message.put("userId", userId);
            message.put("productId", productId);
            message.put("status", "FAILED");
            message.put("reason", reason);
            message.put("timestamp", LocalDateTime.now().toString());
            
            String messageJson = JSON.toJSONString(message);
            
            // 可以发送到专门的失败处理队列
            log.info("秒杀失败消息记录，userId: {}, productId: {}, reason: {}", 
                    userId, productId, reason);
            
        } catch (Exception e) {
            log.error("秒杀失败消息处理异常，userId: {}, productId: {}", userId, productId, e);
        }
    }
}